// Copyright (c) 2020 Presto Labs Pte. Ltd.
// Author: xguo

#pragma once

#include <cstdio>
#include <cstring>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>

#include <glob.h>
#include <unistd.h>
#include <wordexp.h>

inline std::string ExpandUser(const std::string& path) {
  std::string result;
  wordexp_t exp_result;
  int success = wordexp(path.c_str(), &exp_result, 0);
  if (success == 0) {
    result = exp_result.we_wordv[0];
  }
  wordfree(&exp_result);
  return result;
}

inline std::string GetLocalHostname() {
  char buf[1 << 10];
  gethostname(buf, sizeof(buf));
  return std::string(buf);
}

inline std::vector<std::string> Glob(const std::string& pattern) {
  glob_t glob_result;
  std::memset(&glob_result, 0, sizeof(glob_result));

  int return_value = glob(pattern.c_str(), GLOB_TILDE, NULL, &glob_result);
  if (return_value != 0) {
    globfree(&glob_result);
    return {};
  }

  std::vector<std::string> filenames;
  for (size_t i = 0; i < glob_result.gl_pathc; ++i) {
    filenames.push_back(std::string(glob_result.gl_pathv[i]));
  }
  globfree(&glob_result);

  return filenames;
}
